# -*- coding: utf-8 -*-
# created on 2016/11/10

import re
from sympy import sympify, Eq, solve
from mathsolver.functions.base import BaseFunction, BaseFunc, default_symbol, new_latex


class JiJiaJianOu(BaseFunction):
    """F(x)=奇函数±偶函数"""

    @staticmethod
    def transform_right(expr_right):
        if expr_right == sympify('cosh(x)'):
            return sympify('E**x/2 + E**(-x)/2')
        elif expr_right == sympify('sinh(x)'):
            return sympify('E**x/2 - E**(-x)/2')
        else:
            return expr_right

    def solver(self, *args):
        constrains = args[0]

        eq_left, eq_right = args[1].sympify()
        symbol = default_symbol(eq_right)

        pattern = re.compile(r"[a-z]\(%s\)" % str(symbol))
        funcs = sympify(pattern.findall(str(eq_left)))

        # f(x) - g(x) = ...
        eq = Eq(eq_left, eq_right)
        # f(-x) - g(-x) = ...
        eq2 = eq.subs(symbol, -symbol)

        d = {}
        for arg in eq2.lhs.args:
            d.update(solve(constrains, arg))
        # -f(x) - g(x) = ...
        eq2_sub = eq2.subs(d)

        result = solve([eq, eq2_sub], funcs)
        # shuchu = BaseFuncs([{"var": str(symbol), "name": str(left.func), "type": "",
        #                      "expression": self.transform_right(right)} ])

        self.steps.append(["", "根据函数奇偶性有 {}".format(new_latex(constrains))])
        self.steps.append(["", r"\left\{\begin{matrix} %s \\ %s \end{matrix}\right." % (new_latex(eq), new_latex(eq2))])
        self.steps.append(["", r"\left\{\begin{matrix} %s \\ %s \end{matrix}\right." % (new_latex(eq), new_latex(eq2_sub))])

        self.label.add("F(x)=奇函数±偶函数")
        for left, right in result.items():
            func = BaseFunc({"var": str(symbol), "name": str(left.func), "type": "",
                             "expression": self.transform_right(right)})
            self.steps.append(["", "解出 %s" % (func.printing())])
            self.output.append(func)
        return self


if __name__ == '__main__':
    pass
